﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Net;
using System.Text.RegularExpressions;
using EMPower.Utility;
using Qmaker.DAL;
using System.IO;
//from:http://i.aspx1.com
namespace GetNewsService
{
    public class GetNewsMain
    {

        const string SQL1 = "insert into News (NewsID,NewsTitle,NewsAuthor,NewsPubDate,NewsDescription,NewsCategory,NewsBody,NewsUrl) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')";
        const string SQL2 = "select count(*) as Count from News where NewsUrl='{0}'";
        const string SQL3 = "select *  from News";
        public List<RssModel> GetRssList()
        {
            List<RssModel> rssList = new List<RssModel>();
            XmlDocument XML = new XmlDocument();
            XML.Load(getPath()+"\\RssNews.xml");
            XmlNodeList NodeList = XML.SelectNodes("RssNews/NewsSite/Channel[IsGetNews='True']");
            foreach (XmlNode Node in NodeList)
            {
                RssModel rss = new RssModel();
                rss.NewsName = Node["NewsName"].InnerText;
                rss.NewsUrl = Node["NewsUrl"].InnerText;
                rss.StartTag = Node["StartTag"].InnerText;
                rss.EndTag = Node["EndTag"].InnerText;
                rss.ImgStartTag = Node["ImgStartTag"].InnerText;
                rss.ImgEndTag = Node["ImgEndTag"].InnerText;
                rss.IsGetNews = Node["IsGetNews"].InnerText;
                rss.NewsDescription = Node["NewsDescription"].InnerText;
                rss.MaxNewscount = Node["MaxNewscount"].InnerText;
                rss.NewsID = Node["NewsID"].InnerText;
                rss.NewsType = Node["NewsType"].InnerText;
                XmlNode ConfigNode = XML.SelectSingleNode("RssNews/NewsSite/Channel[NewsUrl='" + rss.NewsUrl + "']/Config");
                if (ConfigNode != null)
                {
                    rss.NewsConfig = new NewsConfig();
                    rss.NewsConfig.IsGetA = ConfigNode["IsGetA"].InnerText;
                    rss.NewsConfig.IsGetDIV = ConfigNode["IsGetDIV"].InnerText;
                    rss.NewsConfig.IsGetIMG = ConfigNode["IsGetIMG"].InnerText;
                    rss.NewsConfig.IsGetSPAN = ConfigNode["IsGetSPAN"].InnerText;
                    rss.NewsConfig.IsGetTABLE = ConfigNode["IsGetTABLE"].InnerText;
                }
                rssList.Add(rss);
            }
            return rssList;
        }
        public List<NewsModel> GetNewsList(RssModel rss)
        {
            List<NewsModel> newsList = new List<NewsModel>();
            XmlDocument doc = new XmlDocument();
            long id = IdHelper.GetLongId();
            try
            {
                doc.Load(rss.NewsUrl);
                XmlNodeList NodeList = doc.SelectNodes("//item");
                foreach (XmlNode node in NodeList)
                {
                    NewsModel news = new NewsModel();
                    news.NewsId = id++;
                    #region 获取新闻属性
                    if (node["author"] != null)
                    {
                        news.NewsAuthor = node["author"].InnerText;
                    }
                    if (node["category"] != null)
                    {
                        news.NewsCategory = node["category"].InnerText;
                    }
                    if (node["title"] != null)
                    {
                        news.NewsTitle = node["title"].InnerText;
                    }
                    if (node["description"] != null)
                    {
                        news.NewsDescription = node["description"].InnerText;
                    }
                    else
                    {
                        news.NewsDescription = news.NewsTitle;
                    }
                    if (node["link"] != null)
                    {
                        news.NewsUrl = node["link"].InnerText;
                    }
                    if (node["pubDate"] != null)
                    {
                        news.NewsPubDate = DateTime.Parse(node["pubDate"].InnerText);
                    }
                    #endregion
                    news.Rss = rss;
                    news.NewsType = rss.NewsType;
                    newsList.Add(news);
                }
                return newsList;

            }
            catch (Exception e)
            {
                return newsList;
            }
        }
        static string RemoveHtmlTag(String inputString, string Tag)
        {
            ArrayList TagList = new ArrayList();
            int Top = -1;
            Match m;
            Regex r;
            if (Tag.ToUpper() == "IMG")
            {
                inputString = Regex.Replace(inputString, "\\<" + Tag + @"[\s\S]*?/>", "", RegexOptions.IgnoreCase);
            }
            else
            {
                r = new Regex("\\</?" + Tag, RegexOptions.IgnoreCase | RegexOptions.Compiled);

                for (m = r.Match(inputString); m.Success; )
                {
                    string TagValue = m.Value;
                    int TagIndex = m.Index;
                    if (TagValue.ToUpper() == @"<" + Tag.ToUpper())
                    {
                        Top = TagList.Add(TagIndex);
                        m = m.NextMatch();
                    }
                    else if (TagValue.ToUpper() == @"</" + Tag.ToUpper())
                    {
                        if (TagList.Count > 0)
                        {
                            int DIndex = (int)TagList[Top];
                            inputString = inputString.Remove(DIndex, TagIndex - DIndex + Tag.Length + 3);
                            m = r.Match(inputString);
                        }
                        else
                        {
                            m = m.NextMatch();
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            return inputString;
        }
        public NewsModel GetNewsByNewsLink(NewsModel news)
        {
            object o = new object();
            lock (o)
            {
                string NewsString = "";
                string MyStartTag = news.Rss.StartTag;
                string MyEndTag = news.Rss.EndTag;
                string NewsImg = "";
                string NewsImg1 = "";
                try
                {
                    WebClient MyWebClient = new WebClient();
                    byte[] NewsStringByte = MyWebClient.DownloadData(news.NewsUrl);
                    NewsString = Encoding.Default.GetString(NewsStringByte);
                    Regex r;
                    Match m;
                    if (news.Rss.StartTag != "" && news.Rss.EndTag != "")
                    {
                        r = new Regex(news.Rss.StartTag + @"[\s\S]*?" + news.Rss.EndTag, RegexOptions.IgnoreCase);
                        m = r.Match(NewsString);
                        NewsString = m.Value;
                    }
                    if (news.Rss.ImgStartTag != "" && news.Rss.ImgEndTag != "")
                    {
                        r = new Regex(news.Rss.ImgStartTag + "[\\s\\S]*?" + news.Rss.ImgEndTag, RegexOptions.IgnoreCase);
                        m = r.Match(NewsString);
                        if (m.Success)
                        {
                            NewsImg = m.Value;
                            r = new Regex("\\<IMG" + @"[\s\S]*?>", RegexOptions.IgnoreCase);
                            //m = r.Match(NewsImg);
                            for (m = r.Match(NewsImg); m.Success; m = m.NextMatch())
                            {
                                NewsImg1 += @"<CENTER>" + m.Value + @"</CENTER>";
                            }
                            NewsImg = NewsImg1;
                        }
                    }
                    NewsString = GetNews(NewsString, news);
                    NewsString = NewsImg + NewsString;
                    news.NewsBody = NewsString;
                    return news;
                }
                catch
                {
                    return news;
                }
            }

        }
        static string GetNews(string NewsString, NewsModel news)
        {
            string All = "";
            try
            {
                Regex r;
                Match m;
                r = new Regex("\\<P[^a-z]+(.|\n)*?\\</P\\>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                for (m = r.Match(NewsString); m.Success; m = m.NextMatch())
                {
                    string TempString = m.Value;
                    if (news.Rss.NewsConfig != null)
                    {
                        if (news.Rss.NewsConfig.IsGetTABLE == "FALSE")
                        {
                            TempString = RemoveHtmlTag(TempString, "TABLE");
                            TempString = RemoveHtmlTag(TempString, "iframe");
                            TempString = RemoveHtmlTag(TempString, "TR");
                            TempString = RemoveHtmlTag(TempString, "TD");
                        }
                        if (news.Rss.NewsConfig.IsGetDIV == "FALSE")
                        {
                            TempString = RemoveHtmlTag(TempString, "DIV");
                        }
                        if (news.Rss.NewsConfig.IsGetIMG == "FALSE")
                        {
                            TempString = RemoveHtmlTag(TempString, "IMG");
                        }
                        if (news.Rss.NewsConfig.IsGetA == "FALSE")
                        {
                            TempString = RemoveHtmlTag(TempString, "A");
                        }

                        if (news.Rss.NewsConfig.IsGetSPAN == "FALSE")
                        {
                            TempString = RemoveHtmlTag(TempString, "SPAN");
                        }
                        TempString = RemoveHtmlTag(TempString, "SCRIPT");
                        All += TempString;
                    }
                }
                return All;
            }
            catch
            {
                return All;
            }
        }       
        public List<NewsModel> GetALLNews()
        {
            List<NewsModel> newsList = new List<NewsModel>();
            string sql = "select NewsID,NewsTitle,NewsAuthor,NewsPubDate,NewsDescription,NewsCategory,NewsBody,NewsUrl,DateCreated from news";
            NewsModel news = null;
            using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.ConnectionString, CommandType.Text, sql, null))
            {
                while (reader.Read())
                {
                    news = GetInstanceByDataReader(reader);
                    if (news != null && news.NewsId != 0)
                        newsList.Add(news);
                }
            }


            return newsList;
        }

        /// <summary>
        /// 删除3天以前的新闻
        /// </summary>
        /// <returns></returns>
        public int Delete()
        {
            string sql = "delete from news where DateCreated<DATEADD(D,-3,GETDATE())";
            //SqlParameter[] parms = {
            //        new SqlParameter("@PaperId",SqlDbType.BigInt)
            //    };
            //parms[0].Value = paperId;

            return SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionString, CommandType.Text,sql, null);

        }

        private NewsModel GetInstanceByDataReader(SqlDataReader reader)
        {
            NewsModel current = new NewsModel();
            current.NewsId = reader.IsDBNull(0) ? 0 : reader.GetInt64(0);
            current.NewsTitle = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);
            current.NewsAuthor = reader.IsDBNull(2) ? string.Empty : reader.GetString(2);
            current.NewsPubDate = reader.IsDBNull(3) ? DateTime.Now : reader.GetDateTime(3);
            current.NewsDescription = reader.IsDBNull(4) ? string.Empty : reader.GetString(4);
            current.NewsCategory = reader.IsDBNull(5) ? string.Empty : reader.GetString(5);
            current.NewsBody = reader.IsDBNull(6) ? string.Empty : reader.GetString(6);
            current.NewsUrl = reader.IsDBNull(7) ? string.Empty : reader.GetString(7);
            current.DateCreated = reader.IsDBNull(8) ? DateTime.Now : reader.GetDateTime(8);

            return current;
        } 
        /// <summary>
        /// 批量插入新闻
        /// </summary>
        /// <param name="links"></param>
        /// <returns></returns>
        public bool InsertNews(List<NewsModel> news)
        {
            if (news == null || news.Count == 0)
                return false;
            DataTable dt = new DataTable();
            dt.Columns.Add("NewsId", typeof(long));
            dt.Columns.Add("NewsAuthor", typeof(string));
            dt.Columns.Add("NewsBody", typeof(string));
            dt.Columns.Add("NewsCategory", typeof(string));
            dt.Columns.Add("NewsDescription", typeof(string));
            dt.Columns.Add("NewsPubDate", typeof(DateTime));
            dt.Columns.Add("NewsTitle", typeof(string));
            dt.Columns.Add("NewsType", typeof(int));
            dt.Columns.Add("NewsUrl", typeof(string));            
            dt.Columns.Add("DateCreated", typeof(DateTime));



            foreach (NewsModel l in news)
            {
                DataRow dr = dt.NewRow();
                dr["NewsId"] = l.NewsId;
                dr["NewsAuthor"] = l.NewsAuthor;
                dr["NewsBody"] = l.NewsBody;
                dr["NewsCategory"] = l.NewsCategory;
                dr["NewsDescription"] = l.NewsDescription;
                dr["NewsPubDate"] =l.NewsPubDate.AddHours(8);
                dr["NewsTitle"] = l.NewsTitle;
                dr["NewsType"] = int.Parse(l.NewsType);
                dr["NewsUrl"] = l.NewsUrl;
                dr["DateCreated"] = DateTime.Now;
                dt.Rows.Add(dr);
            }
            using (SqlConnection conn = new SqlConnection(Qmaker.DAL.SqlHelper.ConnectionString))
            {
                conn.Open();
                using (SqlTransaction transaction = conn.BeginTransaction())
                {
                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, transaction))
                    {
                        bulkCopy.BatchSize = 2000;
                        bulkCopy.BulkCopyTimeout = 30;
                        bulkCopy.DestinationTableName = "News";
                        try
                        {
                            foreach (DataColumn col in dt.Columns)
                            {
                                bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
                            }
                            bulkCopy.WriteToServer(dt);
                            transaction.Commit();
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw ex;
                        }
                        finally
                        {
                            conn.Close();
                        }
                    }
                }
            }
            return true;
        }

        public string getPath()
        {
            string key = @"SYSTEM\CurrentControlSet\Services\GetNews";
            string fullPath = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(key).GetValue("ImagePath").ToString();
            fullPath = fullPath.Replace("\"", string.Empty);//替换掉双引号  
            FileInfo fi = new FileInfo(fullPath);
            return fi.Directory.ToString();
        }

    }
}
